package com.boot.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class MyRealm extends AuthorizingRealm {


    /**
     * 授权:通过SecurityUtils.getSubject() 获取到登录后的用户信息
     * Account account = (Account) subject.getPrincipal();
     * 根据account去数据库中查询对应的角色、权限
     * 【但是目前测试案例 我们是将角色、权限都放在了一张表中 所以不需要去额外查询了 但是实际开发中是需要设计在不同的表中的】
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录对象
        Subject subject = SecurityUtils.getSubject();
        String  userName = (String) subject.getPrincipal();
        //根据用户名去数据库中查找到对应的角色、权限标识符

        /**
         * 数据库设计:
         * t_user
         *  userId
         *  userName
         *
         * t_roles
         *  roleId
         *  userId
         *  roleName
         *
         * t_perms
         *   permId
         *   roleId
         *   permName
         */

        //设置角色
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        roles.add("buyer");
        roles.add("seller");
        roles.add("test");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);

        //设置权限
        List<String> perms = new ArrayList<>();
        perms.add("add");
        perms.add("manage");
        perms.add("update");
        perms.add("system:add");//system:add 实际上就是一个字符串
        perms.add("user:order:update");//user:order:update 也是一个字符串
        info.addStringPermissions(perms);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //根据用户去数据库中查找到密码 将账号、密码放到SimpleAuthenticationInfo
        //再和用户输入的账号密码比对
        String username = token.getUsername();
        String password = getPasswordByUsername(username);

        return new SimpleAuthenticationInfo(username,password,getName());
    }

    public String getPasswordByUsername(String userName){
        return "123456";
    }

}

